package project.dade.cn.bst.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.Theme;
import com.alibaba.fastjson.JSON;
import com.squareup.okhttp.Request;

import java.util.HashMap;
import java.util.List;

import butterknife.InjectView;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import project.dade.cn.bst.MainActivity;
import project.dade.cn.bst.R;
import project.dade.cn.bst.adapter.base.MyorderAdapter;
import project.dade.cn.bst.base.ZJPBaseBarActivity;
import project.dade.cn.bst.manager.ApiConfig;
import project.dade.cn.bst.manager.AppApplication;
import project.dade.cn.bst.model.BaseRequestsModel;
import project.dade.cn.bst.model.GsonUtils;
import project.dade.cn.bst.model.MyordrerModel;
import project.dade.cn.bst.network.FormatRequest;
import project.dade.cn.bst.network.callback.ResultCallback;
import project.dade.cn.bst.network.request.OkHttpRequest;
import project.dade.cn.bst.utils.AppUtil;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.NetRequestUtil;
import project.dade.cn.bst.utils.ToastUtil;
import project.dade.cn.bst.views.EmptyLayout;

/**
 * Created by vain zhou on 2016/4/14.
 */
public class MyorderActivity extends ZJPBaseBarActivity implements View.OnClickListener, BGARefreshLayout.BGARefreshLayoutDelegate {
    @InjectView(R.id.error_layout)
    EmptyLayout mErrorLayout;
    @InjectView(R.id.all_order)
    TextView tv_all;
    @InjectView(R.id.payments_order)
    TextView tv_payments;
    @InjectView(R.id.completed_order)
    TextView tv_completed;
    private static ListView recyclerView;
    @InjectView(R.id.view_tab01)
    View view_tab01;
    @InjectView(R.id.view_tab02)
    View view_tab02;
    @InjectView(R.id.view_tab03)
    View view_tab03;
    @InjectView(R.id.rl_recyclerview_refresh)
    BGARefreshLayout mRefreshLayout;
    private static MyorderAdapter myorderAdapter;
    private int type = -1; // 订单类型
    private int page = 1;
    //当前页面数据实体类model
    private MyordrerModel mMyordrerModel;
    public static List<MyordrerModel.MyordrerModelData> Data;
    static Activity mActivity;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myorder);
        recyclerView = (ListView) findViewById(R.id.rv_recyclerview_data);
        mActivity = MyorderActivity.this;
        tv_all.setOnClickListener(this);
        tv_payments.setOnClickListener(this);
        tv_completed.setOnClickListener(this);
        requestGetorder();
        mRefreshLayout.setDelegate(this);
        mRefreshLayout.setRefreshViewHolder(new BGANormalRefreshViewHolder(MyorderActivity.this, true));
        changeTab(0);
    }

    private void changeTab(int tab) {
        if (tab == 0) {
            tv_all.setTextColor(getResources().getColor(R.color.primary));
            view_tab01.setVisibility(View.VISIBLE);

        } else {
            tv_all.setTextColor(getResources().getColor(R.color.black_333));
            view_tab01.setVisibility(View.GONE);
        }
        if (tab == 1) {
            tv_payments.setTextColor(getResources().getColor(R.color.primary));
            view_tab02.setVisibility(View.VISIBLE);
            type = 0;
        } else {
            tv_payments.setTextColor(getResources().getColor(R.color.black_333));
            view_tab02.setVisibility(View.GONE);
        }
        if (tab == 2) {
            tv_completed.setTextColor(getResources().getColor(R.color.primary));
            view_tab03.setVisibility(View.VISIBLE);
            type =2;
        } else {
            tv_completed.setTextColor(getResources().getColor(R.color.black_333));
            view_tab03.setVisibility(View.GONE);

        }
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        initRequest();
//    }

    private void initRequest() {
        if (AppUtil.isNetworkAvailable(this)) {
            requestGetorder();
        } else {
            mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        }

    }

    private void requestGetorder() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("uid", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("mobilephone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
        params.put("pageindex", page + "");
        params.put("pstatus", type + "");
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Orderlist).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                        mRefreshLayout.endRefreshing();
                        ToastUtil.showShort(MyorderActivity.this, "网络相应失败请稍后再试");
                    }

                    @Override
                    public void onResponse(String response) {
                        mRefreshLayout.endRefreshing();
                        LogUtil.i(TAG, "获取订单列表：" + response);
                        if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "获取订单列表"))) {
                            mMyordrerModel = GsonUtils.jsonToBean(response, MyordrerModel.class);
                            if (mMyordrerModel.getResult() == 0) {
                                if(mMyordrerModel.getData()==null){
                                    mErrorLayout.setErrorType(EmptyLayout.NODATA);
                                   mErrorLayout.setErrorMessage("啊哦！这里没有订单哦");
                                }else {
                                    mErrorLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                                    Data = mMyordrerModel.getData();
                                    myorderAdapter = new MyorderAdapter(MyorderActivity.this, Data);
                                    recyclerView.setAdapter(myorderAdapter);
                                }

                            }
                        } else {
                            mRefreshLayout.endRefreshing();
                            mRefreshLayout.endLoadingMore();
                            ToastUtil.showShort(MyorderActivity.this, NetRequestUtil.requestsError(response, "获取订单列表"));
                            mErrorLayout.setErrorType(EmptyLayout.NODATA);
                            mErrorLayout.setErrorMessage("数据请求失误");

                        }
                    }

                });
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        if (AppUtil.isNetworkAvailable(this)) {
            page = 1;
            requestGetorder();
        } else {
            mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        }

    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        if (AppUtil.isNetworkAvailable(this)) {
            page++;
            requestAddGetorder();
        } else {
            mRefreshLayout.endLoadingMore();
            Snackbar.make(recyclerView, R.string.tips_network_error, Snackbar.LENGTH_SHORT).show();
        }
        return true;
    }

    private void requestAddGetorder() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("uid", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("mobilephone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
        params.put("pageindex", page + "");
        params.put("pstatus", type + "");
        LogUtil.i(TAG, "获取订单列表类型：" + type + "");
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Orderlist).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                        mRefreshLayout.endLoadingMore();
                        ToastUtil.showShort(MyorderActivity.this, "网络相应失败请稍后再试");
                    }

                    @Override
                    public void onResponse(String response) {
                        mRefreshLayout.endLoadingMore();
                        LogUtil.i(TAG, "获取订单列表：" + response);
                        if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "获取订单列表"))) {
                            mMyordrerModel = GsonUtils.jsonToBean(response, MyordrerModel.class);
                            //获取请求
                            if (mMyordrerModel.getResult() == 0) {
                                if (mMyordrerModel.getData() == null) {
                                    ToastUtil.showShort(MyorderActivity.this, "已经没了哦");
                                    page--;
                                } else {
                                    Data.addAll(mMyordrerModel.getData().size(),mMyordrerModel.getData());
                                    myorderAdapter.notifyDataSetChanged();
                                }
                            }
                        } else {
                            page--;
                            mRefreshLayout.endLoadingMore();
                            ToastUtil.showShort(MyorderActivity.this, NetRequestUtil.requestsError(response, "获取订单列表"));
                            mErrorLayout.setErrorType(EmptyLayout.NODATA);
                            mErrorLayout.setErrorMessage("数据请求失误");
                        }
                    }

                });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.all_order:
                changeTab(0);
                type = -1;
                page = 1;
                initRequest();
                break;
            case R.id.payments_order:
                changeTab(1);
                type = 0;
                page = 1;
                initRequest();
                break;
            case R.id.completed_order:
                changeTab(2);
                type = 2;
                page = 1;
                initRequest();
                break;
        }

    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void delete(View view) {
        final String id = view.getTag() + "";
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("uid", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("mobilephone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
        params.put("orderno",Data.get(Integer.parseInt(id)).getOrderNo());
        params.put("Sign", FormatRequest.main(params));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Orderdelete).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                        ToastUtil.showShort(mActivity, "网络相应失败请稍后再试");
                    }

                    @Override
                    public void onResponse(String response) {
                        LogUtil.i(TAG, "获取：" + response);
                        BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                        if ( model.getResult() == 0) {
                            Data.remove(Integer.parseInt(id));
                            myorderAdapter = new MyorderAdapter(MyorderActivity.this, Data);
                            recyclerView.setAdapter(myorderAdapter);
                        } else {
                            ToastUtil.showShort(mActivity, NetRequestUtil.requestsError(response, ""));
                        }
                    }

                });
    }

    public void receipt(View view) {
        final String id = view.getTag() + "";
        new MaterialDialog.Builder(MyorderActivity.this)
                .title(R.string.tips_title)
                .titleColor(getResources().getColor(R.color.background_material_dark))
                .theme(Theme.LIGHT)
                .content(R.string.tips_connect_confirm)
                .positiveText(R.string.ok)
                .negativeText(R.string.cancel)
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {

                        HashMap<String, String> params = new HashMap<String, String>();
                        params.put("uid", AppApplication.getInstance().getSpUtil().getUserID().toString());
                        params.put("mobilephone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
                        LogUtil.i(TAG, "获取订单号：" + Data.get(Integer.parseInt(id)).getOrderNo());
                        params.put("orderno",Data.get(Integer.parseInt(id)).getOrderNo());
                        params.put("Sign", FormatRequest.main(params));
                        new OkHttpRequest.Builder()
                                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Ordercomnfirm).params(params)
                                .post(new ResultCallback<String>() {
                                    @Override
                                    public void onError(Request request, Exception e) {
                                        ToastUtil.showShort(MyorderActivity.this, "网络相应失败请稍后再试");
                                    }

                                    @Override
                                    public void onResponse(String response) {
                                        LogUtil.i(TAG, "获取：" + response);
                                        BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                                        if (model.getResult() == 0) {
                                            Data.get(Integer.parseInt(id)).setOrderStatus(5);
                                            myorderAdapter = new MyorderAdapter(MyorderActivity.this, Data);
                                            recyclerView.setAdapter(myorderAdapter);
                                        } else {

                                            ToastUtil.showShort(MyorderActivity.this, NetRequestUtil.requestsError(response, ""));
                                                                      }
                                                                  }

                                                              });

                                                  }

                }).show();



    }

    }


